﻿//# define DEBUG_AGENT

using System.Windows;


using System.Threading;
using System.Linq;
using System.Xml.Linq;
using System;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Media.Imaging;
using Microsoft.Phone;
using System.Windows.Threading;
using OnlineVideos.Library;
using System.Globalization;
using Microsoft.Phone.Net.NetworkInformation;
using OnlineVideos;
using Common.Library;
using OnlineVideos.Common;
using Microsoft.Phone.Scheduler;
using System.Threading.Tasks;
using Windows.Storage;
using System.Text;
using Windows.Storage.Streams;
//using Common.Common;

namespace OnlineVideos.BackgroundAgent
{
    public class ScheduledSyncAgent : ScheduledTaskAgent, IDowloadCompleteCallback
    {
        public AutoResetEvent auto = new AutoResetEvent(false);
        public void AutoComplete()
        {

            Timer timer = new Timer(state =>
            {


                OnStartEvent();

            },
                null,
                TimeSpan.FromSeconds(23),
                TimeSpan.FromSeconds(23));
        }
        protected  async override void OnInvoke(ScheduledTask task)
        {
            try
            {
              


                if (AppSettings.AppStatus != ApplicationStatus.Launching && AppSettings.AppStatus != ApplicationStatus.Active)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        try
                        {
                            SQLite.SQLiteAsyncConnection conn = new SQLite.SQLiteAsyncConnection(Constants.DataBaseConnectionstringForSqlite);
                            Constants.connection = conn;
                        }
                        finally
                        {
                            auto.Set();
                        }
                    });
                    auto.WaitOne();
                    SyncAgentState.SyncAgent = this;
                    AutoComplete();
                    switch (AppSettings.BackgroundAgentStatus)
                    {
                        case SyncAgentStatus.DownloadFavourites:
                            AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadParentalControlPreferences;
                            break;
                        case SyncAgentStatus.UploadFavourites:
                            AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadParentalControlPreferences;
                            break;
                        case SyncAgentStatus.RestoreStory:
                               AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadParentalControlPreferences;
                            break;
                        case SyncAgentStatus.UploadStory:
                            AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadParentalControlPreferences;
                            break;
                        //    if (AppSettings.DownloadFavCompleted == false && AppSettings.SkyDriveLogin == true)
                        //    {
                        //        ReStoreFavourites reStoreFav = new ReStoreFavourites();
                        //        if (reStoreFav.LoginStatus() == false)
                        //            await SyncButton.login();
                        //        await reStoreFav.RestorefavFolder(ResourceHelper.ProjectName);

                        //        OnStartEvent();

                        //    }
                        //    else
                        //    {
                        //        AppSettings.BackgroundAgentStatus = SyncAgentStatus.UploadFavourites;
                        //        OnStartEvent();
                        //    }
                        //    break;
                        //case SyncAgentStatus.UploadFavourites:
                        //    if (AppSettings.SkyDriveLogin == true && Task.Run(async () => await Storage.FavouriteFileExists("Favourites.xml")).Result)
                        //    {

                        //        SyncStories.UploadFavourites upLoad = new SyncStories.UploadFavourites();
                        //        if (upLoad.LoginStatus() == false)
                        //            await SyncButton.login();
                        //        await upLoad.CreateFolderForFav(ResourceHelper.ProjectName);

                        //        OnStartEvent();
                        //    }
                        //    else
                        //    {
                        //        AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadParentalControlPreferences;
                        //        OnStartEvent();
                        //    }
                        //    break;

                        //case SyncAgentStatus.RestoreStory:
                        //    if (AppSettings.DownloadStoryCompleted == false && AppSettings.SkyDriveLogin == true && (ResourceHelper.ProjectName == "Story Time" || ResourceHelper.ProjectName == "Vedic Library"))
                        //    {
                        //        RestoreStory reStorestory = new RestoreStory();
                        //        if (reStorestory.LoginStatus() == false)
                        //            await SyncButton.login();
                        //        if (ResourceHelper.ProjectName == "Story Time")
                        //            await reStorestory.RestoreFolder("StoryRecordings");
                        //        else
                        //            await reStorestory.RestoreFolder("VedicRecordings");

                        //        OnStartEvent();
                        //    }
                        //    else
                        //    {
                        //        AppSettings.BackgroundAgentStatus = SyncAgentStatus.UploadStory;
                        //        OnStartEvent();
                        //    }
                        //    break;
                        //case SyncAgentStatus.UploadStory:
                        //    if (AppSettings.SkyDriveLogin == true && (ResourceHelper.ProjectName == "Story Time" || ResourceHelper.ProjectName == "Vedic Library"))
                        //    {
                        //        SyncStories.UploadStory upLoad = new SyncStories.UploadStory();
                        //        if (upLoad.LoginStatus() == false)
                        //            await SyncButton.login();
                        //        if (ResourceHelper.ProjectName == "Story Time")
                        //            await upLoad.CreateFolder("StoryRecordings");
                        //        else
                        //            await upLoad.CreateFolder("VedicRecordings");

                        //        OnStartEvent();
                        //    }
                        //    else
                        //    {
                        //        AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadFavourites;
                        //        OnStartEvent();
                        //    }
                        //    break;
                        default:
                            ShowDownloader.StartBackgroundDownload();
                            break;
                    }


                }
                else
                {
                    OnStartEvent();
                }

            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in OnInvoke Method In ScheduledSyncAgent.cs file", ex);
            }
          
        }

        public void OnStartEvent()
        {
            try
            {
                //DownloadLog(AppSettings.BackgroundAgentStatus.ToString());
//#if(DEBUG_AGENT)
//                ScheduledActionService.LaunchForTest(ResourceHelper.ProjectName, TimeSpan.FromSeconds(61));
//#endif

                NotifyComplete();
                //LiveTileHelper.UpdateFromXmlFile(ResourceHelper.ProjectName);
             
               


            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in OnStartEvent Method In ScheduledSyncAgent.cs file", ex);
            }
        }
        //public  void DownloadLog(string DownloadStatus)
        //{
        //    try
        //    {
        //        IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
        //        IsolatedStorageFileStream isoStream = null;
        //        XDocument xdoc = null;
        //        if (isoStore.FileExists("/BackAgentStatus.xml"))
        //        {
        //            isoStream = new IsolatedStorageFileStream("/BackAgentStatus.xml", FileMode.Open, isoStore);
        //            xdoc = XDocument.Load(isoStream);
        //            isoStream.Close();
        //            xdoc.Root.Add(new XElement("Status", DownloadStatus));

        //            isoStream = new IsolatedStorageFileStream("/BackAgentStatus.xml", FileMode.Create, isoStore);
        //            xdoc.Save(isoStream);
        //            isoStream.Close();

        //        }
        //        else
        //        {
        //            isoStream = new IsolatedStorageFileStream("/BackAgentStatus.xml", FileMode.Create, isoStore);
        //            xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
        //                        new XElement("Item",
        //                                new XElement("Status", DownloadStatus)));

        //            xdoc.Save(isoStream);
        //            isoStream.Close();
        //        }
               
        //    }
        //    catch (Exception ex)
        //    {
              
        //    }
        //}
    }
}